<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left" :model="formModel" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :sm="24">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model.trim="formModel.taskName" autocomplete="off" placeholder="请输入任务名称" />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务描述" prop="description">
            <el-input v-model.trim="formModel.description" autosize type="textarea" placeholder="请输入任务描述" />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务教室" prop="target">
            <el-select class="w100" v-model="formModel.target" filterable multiple placeholder="请选择任务教室" autocomplete="off">
              <el-option v-for="item in roomStore.roomAllList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24">

          <el-form-item label="任务模式" prop="cronSpec">
            <div class="d-flex flex-column text-white">
              <div>
                <el-radio-group v-model="formModel.cronSpec">
                  <el-radio label="day">每天一次</el-radio>
                  <el-radio label="week">每周一次</el-radio>
                </el-radio-group>
              </div>
              <div v-show="formModel.cronSpec == 'day'">
                每天
                <el-time-picker v-model="formModel.taskHour" format='HH:mm' value-format="HH:mm" placeholder="选择时间" style="width: 140px" />
                <!-- <el-time-select v-model="formModel.taskHour" :picker-options="{ start: '00:00', step: '00:01', end: '23:59' }" placeholder="选择时间" style="width: 140px">
                </el-time-select> -->
                执行

              </div>
              <div v-show="formModel.cronSpec == 'week'">
                每
                <el-select v-model="formModel.taskDay" style="width: 140px" placeholder="请选择任务状态" autocomplete="off">
                  <el-option label="周一" :value="1"></el-option>
                  <el-option label="周二" :value="2"></el-option>
                  <el-option label="周三" :value="3"></el-option>
                  <el-option label="周四" :value="4"></el-option>
                  <el-option label="周五" :value="5"></el-option>
                  <el-option label="周六" :value="6"></el-option>
                  <el-option label="周日" :value="0"></el-option>
                </el-select>,
                <el-time-picker v-model="formModel.taskHour" format='HH:mm' value-format="HH:mm" placeholder="选择时间" style="width: 140px" />
                <!-- <el-time-select v-model="formModel.taskHour" :picker-options="{ start: '00:00', step: '00:01', end: '23:59' }" placeholder="选择时间" style="width: 140px"> 
                </el-time-select>
                  -->
                执行

              </div>
            </div>
          </el-form-item>

        </el-col>

        <el-col :sm="24">
          <el-form-item label="任务指令" prop="taskInstructions">
            <el-radio-group v-model="formModel.taskInstructions" size="mini">
              <el-radio label="1">一键上课</el-radio>
              <el-radio label="0">一键下课</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务状态" prop="status">
            <el-radio-group v-model="formModel.status" size="mini">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>
  
<script setup>
/**
* 编辑新增任务
*/
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { getNewObj } from '@/utils/EsCommon';
import { RegRule } from '@/utils/EsValidate';
import ImageUpload from '@/components/upload/ImageUpload.vue';
import useRoomStore from '@/stores/useRoomStore';

// ======================================================
//                      变量声明
// ======================================================
const roomStore = useRoomStore();

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = {
  id: 0,
  taskInstructions: "",
  status: '1',
  description: "",
  taskName: "",
  cronSpec: "",
  taskHour: "",
  taskDay: "",
  target: [],
  command: "",

};

const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '600px',
})
// 表单组件的引用实例
const formRef = ref(null);
// 加载状态

// 选项数据
// 分类ID树形选项数据
const bildingList = ref([]);
// 是否热门选项数据
const optionsOfIsHot = ref({});
// 是否推荐选项数据
const optionsOfIsRecommend = ref({});
// 状态选项数据
const optionsOfStatus = ref({});
// 表单校验规则
const formRules = ref({
  taskName: [
    { required: true, trigger: "blur", message: "请输入任务名称" },
  ],
  target: [
    { required: true, trigger: "blur", message: "请选择任务教室" },
  ],
  taskInstructions: [
    { required: true, trigger: "blur", message: "请选择任务指令" },
  ],
  status: [
    { required: true, trigger: "blur", message: "请选择任务状态" },
  ],
})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    let _formModel = getNewObj(formModel.value)

    let params = {
      id: Number(_formModel.id),
      status: Number(_formModel.status),
      description: _formModel.description,
      taskName: _formModel.taskName,
      cronSpec: _formModel.cronSpec,
      taskHour: _formModel.taskHour,
      taskDay: Number(_formModel.taskDay),
      target: _formModel.target.join(","),
      command: JSON.stringify([{
        joinNum: 1,
        value: _formModel.taskInstructions,
      }]),
      //   "status": 1,
      // "description": "上课",
      // "taskName": "上课",
      // "cronSpec": "day",
      // "taskHour": "09:00",
      // "target": "109",
      // "command": "[{\"joinNum\":1,\"value\":\"1\"}]"


    }
    if (params.id == 0) {
      delete params.id
    }


    EsAjax.post(ApiUrls.taskEdit, params).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  })
}

// 点击重置表单按钮
const onReset = () => {
  ElMessageBox.confirm('确定要重置表单数据吗？').then(() => {
    formRef.value.resetFields();
  }).catch(() => { })
}

// 点击取消按钮
const onCancel = () => {
  formModel.value = Object.assign({}, formAttrs);
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
}

// ======================================================
//                      处理事件
// ======================================================


// 加载数据
const show = (id, title, item = null, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;

  roomStore.getRoomAllList()
  formModel.value = Object.assign({}, formAttrs);
  if (item) {
    item = getNewObj(item)

    formModel.value = Object.assign({ ...formAttrs }, getNewObj(item));
    console.log(formModel.value);
    if (`${item.status}`) formModel.value.status = `${item.status}`
    if (item.command) formModel.value.taskInstructions = JSON.parse(item.command)[0].value
    if (item.target) formModel.value.target = item.target.split(",")
    else item.target = []
    console.log(formModel.value)
  }

}

defineExpose({
  show
})
</script>
<style lang="less" >
.el-time-panel__btn.cancel {
  color: #fff;
}
.el-time-spinner {
  background: #070b3c !important;
}
.el-time-spinner__item.is-active,
.el-time-spinner__item.is-active:not(.is-disabled) {
  color: #fff !important;
}
</style>